/*
** broadcast.c for zappy in /home/guidet_m/TECK2/projets/zappy/server_zappy
** 
** Made by michael guidet
** Login   <guidet_m@epitech.net>
** 
** Started on  Mon Jul  4 15:40:57 2011 michael guidet
** Last update Mon Jul 11 10:14:43 2011 michael guidet
*/

#include <math.h>
#include "server.h"

void	graph_broadcast(t_env *e, t_fd *fd, char *cmd)
{
  t_fd	*tmp;
  char	*cmd2;

  cmd2 = x_null(NULL, malloc(sizeof(*cmd2) * (strlen(&cmd[10]) + 16)),
		"malloc");
  sprintf(cmd2, "pbc %d %s\n", fd->pl->id, &cmd[10]);
  for (tmp = e->fd; tmp; tmp = tmp->next)
    if (tmp->type == GRAPH)
      add_string_to_list(&tmp->send_list, cmd2);
  exit(-1);
  free(cmd2);
}

void		broadcast_contenu(char **cmd2, t_fd *fd, t_env *e, char *cmd)
{
  t_fd		*tmp;
  t_coord	new;
  t_coord	drone_pos = {fd->pl->x, fd->pl->y};
  static int	len = BUF_SIZE;

  for (tmp = e->fd; tmp; tmp = tmp->next)
    if (tmp->type == AI && tmp != fd)
      {
	memset((*cmd2), 0, (BUF_SIZE) + 1);
	t_coord tmp_pos = {tmp->pl->x, tmp->pl->y};
	broadcast_pos(drone_pos, tmp_pos, &new, e);
	int dir = action_broadcast_direction(new.x, new.y);
	if (dir == SAME_PLACE)
	  sprintf((*cmd2), "message %d,", 0);
	else if (tmp->pl->look_at == NORD)
	  sprintf((*cmd2), "message %d,", dir);
	else if (tmp->pl->look_at == OUEST)
	  sprintf((*cmd2), "message %d,", (dir + 5) % 8 + 1);
	else if (tmp->pl->look_at == SUD)
	  sprintf((*cmd2), "message %d,", (dir + 3) % 8 + 1);
	else if (tmp->pl->look_at == EST)
	  sprintf((*cmd2), "message %d,", (dir + 1) % 8 + 1);
	xstrcat(&(*cmd2), &cmd[10], &len);
	add_string_to_list(&tmp->send_list, (*cmd2));
      }
}

void	action_broadcast(t_fd *fd, t_env *e, char *cmd)
{
  char	*cmd2;

  if (!action_broadcast_init(fd, cmd, &cmd2))
    return ;
  broadcast_contenu(&cmd2, fd, e, cmd);
  free(cmd2);
  add_string_to_list(&fd->send_list, "ok\n");
  graph_broadcast(e, fd, cmd);
}

int	action_broadcast_init(t_fd *fd, char *cmd, char **cmd2)
{
  printf("%sDrone %d %s Execute %s%s\n", PURPLE, fd->pl->id,
	 fd->pl->team, cmd, DEFAUT);
  fd->wait = -1;
  fd->idaction = -1;
  if (strlen(&cmd[10]) > 0)
    {
      add_string_to_list(&fd->send_list, "ko\n");
      return (0);
    }
  (*cmd2) = x_null(NULL, malloc(sizeof(char) * (BUF_SIZE + 1)), "malloc");
  return (1);
}

int	action_broadcast_direction(int dest_x, int dest_y)
{
  float	angle;

  if (dest_x == 0 && dest_y == 0)
    return (SAME_PLACE);
  if (dest_x == 0)
    return ((dest_y > 0 ? NORD : SUD));
  if (dest_y == 0)
    return ((dest_x > 0 ? EST : OUEST));
  angle = dest_y ? atanf((float)ABS(dest_y) / (float)ABS(dest_x)) :
    atanf((float)ABS(dest_x) / (float)ABS(dest_y));
  if (angle < M_PI / 8.0f)
    return ((dest_x > 0) ? (OUEST) : (EST));
  if (angle < (3.0f * M_PI) / 8.0f)
    {
      if (dest_x > 0)
	return ((dest_y > 0) ? (NORD_OUEST) : (SUD_OUEST));
      else
	return ((dest_y > 0) ? (NORD_EST) : (SUD_EST));
    }
  else
    return ((dest_y > 0) ? (NORD) : (SUD));
  return (0);
}
